package shared

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var DB *gorm.DB

func GetDB() *gorm.DB {
	dsn := ConfigService.GetAppConfig().DataSource.Dsn

	gormConfig := gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "op_", // Table name prefix, table for `User` would be `t_users`
			SingularTable: true,  // Uses singular table name, table for `User` would be `user` with this option enabled
		},
		// GORM performs write (create/update/delete) operations run inside a transaction to ensure data consistency,
		// you can disable it during initialization if it is not required, you will gain about 30%+ performance improvement after that.
		//SkipDefaultTransaction: true,
	}

	// Refers https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	db, err := gorm.Open(mysql.Open(dsn), &gormConfig)

	if err != nil {
		println("Failed to connect database")
		return nil
	}

	return db
}